package com.fastexport.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.fastexport.constant.Watermark;
import com.fastexport.handler.PresetWatermarkSheetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class FastExportWithCacheUtils {

    private static final Logger logger = LoggerFactory.getLogger(FastExportUtils.class);

    private static final String cachePath = "D:\\test\\cache";

    public static void export(List<?> list, String cacheFolder) {
        HttpServletResponse response = HttpContextUtils.getHttpServletResponse();
        export(response, list, cacheFolder);
    }

    public static void export(List<?> list, String fileName, String cacheFolder) {
        HttpServletResponse response = HttpContextUtils.getHttpServletResponse();
        export(response, list, fileName, cacheFolder);
    }

    public static void export(HttpServletResponse response, List<?> list, String cacheFolder) {
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        export(response, list, fileName, cacheFolder);
    }

    public static void export(HttpServletResponse response, List<?> list, String fileName, String cacheFolder) {
        String sheetName = "sheet1";
        export(response, list, fileName, sheetName, cacheFolder);
    }

    public static void export(HttpServletResponse response, List<?> list, String fileName, String sheetName, String cacheFolder) {
        ExcelWriterSheetBuilder builder = getWriterSheetBuilder(response, list, fileName, sheetName, cacheFolder);
        builder.doWrite(list);
    }

    public static ExcelWriterSheetBuilder getWriterSheetBuilder(HttpServletResponse response, List<?> list, String fileName, String sheetName, String cacheFolder) {
        ValidateUtils.validateInputs(response, list);
        fileName = ValidateUtils.fileNameHandle(fileName);
        BaseHandlerUtils.setResponse(response, fileName);

        Class<?> aClass = list.get(0).getClass();
        List<?> headList = BaseHandlerUtils.getHeadList(list);

        cacheFolder = cacheFolder + File.separator + "cacheFile" + ".xlsx";
        Path path = Paths.get(cacheFolder);
        try (OutputStream bos = Files.newOutputStream(path)) {
            // 写入内存流
            EasyExcel.write(bos, aClass)
                    .inMemory(true)
                    .registerWriteHandler(new PresetWatermarkSheetHandler(new Watermark()))
                    .sheet(sheetName)
                    .doWrite(headList);

            // 将内存流转换为InputStream
            InputStream templateInputStream = Files.newInputStream(path);
            // 直接从内存流读取模板并写入响应
            return EasyExcel.write(response.getOutputStream(), aClass)
                    .withTemplate(templateInputStream)
                    .sheet(sheetName)
                    .needHead(false);
        } catch (Exception e) {
            logger.error("Error during Excel export.", e);
            throw new RuntimeException("Error during Excel export.", e);
        }
    }

}
